const app = getApp();
import { zg99Request, hbappRequest } from "/utils/requests";
var share = false;
var isMe = false;
var user = null;
var cjCishu = 0;
let status = false;
Page({
    data: {
        showIcon: !0,
        isShowAuth: !1,
        total: 0,
        sliderDisabled: "",
        awardsList: {}, //转盘临时存储奖项信息
        animationData: {}, //转盘设置
        btnDisabled: "",
        awardsLen: 0, //转盘临时存储奖项列表
        flag: true, //是否有抽奖机会
        rules_flag: false, //规则是否展示
        prize: '', //
        prize_jgg: '', //九宫格
        last_index: 0, //上一回滚动的位置
        amplification_index: -1, //轮盘的当前滚动位置
        roll_flag: true, //是否允许滚动
        speed: 300, //速度，速度值越大，则越慢 初始化为300
        finalindex: 6, //最终的奖励距离当前的位置！不是最后的几等奖！
        max_number: 8, //九宫格奖项数量
        myInterval: "", //定时器
        max_speed: 40, //滚盘的最大速度
        minturns: 5, //最小的圈数为2，2+10随机
        runs_now: 0, //当前已跑步数
        time: 0,
        blind_result: '', //盲盒结果
        prize_num: 0, //中奖结果
        prizes: {}, //奖项信息
        myPhone: '',
        result_show: false,
        result: {},
        userInfo: {},
        winners: [],
        shname: '',
        address: '',
        avatarUrl: '',
        xulieName: '',
        realname: '',
        items: [], //多项目
        index_xm: -1,
        items_flag: '', //是否多项目。多项目 图书 优惠券 资料 网课需要弹出选择项目
        item: '', //提交到99后台项目
        options: null,
        start_time: '',
        end_time: '',
        index_jx: 0,
        nainjiArr: [{
            id: "1_1",
            text: "大一"
        }, {
            id: "1_2",
            text: "大二"
        }, {
            id: "1_3",
            text: "大三"
        }, {
            id: "1_4",
            text: "大四"
        }, {
            id: "1_5",
            text: "研一"
        }, {
            id: "1_6",
            text: "研二"
        }, {
            id: "1_7",
            text: "研三"
        }],
        gxxx: false,
    },
    async onLoad(options) {
        this.setData(await app.methods.myPhone()); // 获取本地存储手机号
        if(!this.data.myPhone) {
            await app.methods.getPhoneNumber()
            this.setData({
              isShowAuth: !0
            })
        }
        xhs.showLoading({
            title: '数据加载中....',
            mask: true
        })
        xhs.showShareMenu({
          shareTypes: 'normal',
        })
        // 直接打开分享的链接（options是个对象，可以直接使用）
        // 扫码打开的小程序（也是个对象，但是需要解析scene值）（和小程序复制链接获取的一样）
        let links, jxOptions = null;
        if (options.scene) {
            options.scene = options.scene.replace(/%253D/g, ".");
            options.scene = options.scene.replace(/%2526/g, "-");
            jxOptions = await app.methods.getOPtions(options);
        }
        if (options.data) {
            let data1 = JSON.parse(decodeURIComponent(options.data));
            options = data1
        }
        let id = options.scene ? jxOptions.id : options.id ? options.id : null;
        options.id = id;
        if(id) links = await app.methods.getLink(id);
        if(links) {
            options.hdid = links.hdid ? links.hdid : '';
            options.lx = links.lx ? links.lx : null;
            options.rq = links.rq ? links.rq : null;
        }
        options.fx = options.scene ? jxOptions.fx : options.fx;
        options.gh = options.scene ? jxOptions.gh : options.gh;
        options.xzrPhone = options.xzrPhone ? options.xzrPhone : null;
        share = options.lx || links.lx ? true : false;
        isMe = options.xzrPhone && options.xzrPhone == myPhone ? true : false;
        // console.log(options)
        await this.getHdInfo(options.hdid)
        this.setData(await app.methods.getIdentity(options)); // 获取个人身份信息
        if(this.data.getIdentity.crm) {
            options.wxh = this.data.getIdentity.crm;
        } else {
            options.wxh = options.gh;
        }
        this.setData(await app.methods.getWechat(options)); // 获取个人身份信息
        this.setData(await app.methods.guishudi(options)); // 获取归属地
        let fenbu = this.data.fenbu;
        let fenxiao = this.data.fenxiao;
        let getIdentity = this.data.getIdentity;
        getIdentity.fenbu = fenbu;
        getIdentity.fenxiao = fenxiao;
        getIdentity.zzname = this.data.zzname;
        getIdentity.zzid = this.data.zzid;
        getIdentity.erpdqm = this.data.erpdqm;
        let { myPhone } = this.data;
        if (myPhone) {
            user = await app.methods.getphonestatusCX(myPhone, this.data.prizes.actid, 'choujiang')
            if(!user?.user?.user?.zhuanye && options.rq == 'gx') {
                this.setData({
                    gxxx: true
                })
            }
        }
        const backgroundColor = this.data.prizes.style == 1 ? '#d80015' : this.data.prizes.style == 2 ? '#0500d8' : this.data.prizes.style == 3 ? '#ff9adf' : this.data.prizes.style == 4 ? "#ff8400" : this.data.prizes.style == 5 ? '#1aac16' : '#d80015'
        xhs.setNavigationBarColor({
            backgroundColor,
            frontColor: '#ffffff',
        })
        if (share) {
            if (myPhone) {
                let xzCishu = await this.getCount(this.data.prizes.actid, {
                    phone: myPhone,
                    tabnum: 1,
                    limits: 200
                });
                xzCishu = xzCishu ? xzCishu : 0;
                cjCishu = user.user ? user?.user?.user?.cjcishu : ''
                if (!isMe) {
                    if (options.xzrPhone && !user.user) {
                        xhs.showToast({
                            title: '抽奖一次即可完成助力~',
                            icon: 'none',
                            duration: 2000
                        })
                    } else if (options.xzrPhone && user.user.user.xzrPhone) {
                        xhs.showToast({
                            title: user.user.user.xzrPhone !== options.xzrPhone ? '已为其他好友助力' : '已为好友助力',
                            icon: 'error',
                            duration: 2000
                        })
                    }
                }
                const total = user.user ? Number(cjCishu) - Number(xzCishu) : 1;
                this.setData({
                    total
                })
            } else {
                if (options.xzrPhone) {
                    xhs.showToast({
                        title: '抽奖一次即可完成助力~',
                        icon: 'none',
                        duration: 2000
                    })
                }
            }
        }
        this.setData({
            getIdentity,
            options,
            max_number: this.data.prizes.lists.length
            // result_show: true,
            // gxxx: true,
        })
        xhs.showLoading({
            title: '数据加载完毕！',
        })
        setTimeout(function () {
            xhs.hideLoading()
        }, 1000)
        console.log(this.data)
        // console.log(options)
    },
    // 获取活动信息
    getHdInfo(mid) {
        return new Promise(resolve => {
            hbappRequest({
                url: `/hbqt/web/index.php/Contactus/xcxhd/index_luckdraw_list?callback=&`,
                method: "GET",
                dataType: "jsonp",
                data: {
                    mid
                },
            }).then(res => {
                let lottery = app.methods.getAPIReturn(res);
                // console.log(lottery)
                var lists = lottery.data.lists.substr(2, lottery.data.lists.length - 4).split('},{');
                for (let i = 0; i < lists.length; i++) {
                    lists[i] = "{" + lists[i] + "}";
                    lists[i] = JSON.parse(lists[i])
                }
                const showLists = lists.sort(this.compare('prizeid'))
                this.setData({
                    prizes: lottery.data,
                    showLists,
                    items_flag: lottery.data.xiangmu,
                    ['prizes.lists']: lists,
                    start_time: this.formatDate(lottery.data.start_time) / 1000,
                    end_time: this.formatDate(lottery.data.end_time) / 1000,
                    ['prizes.poster_flag']: lottery.data.poster_flag,
                    // max_number: lottery.lists.length
                })
                app.globalData.laiyuan = `${mid}抽奖`
                //奖项配置
                app.awardsConfig = {
                    chance: !0,
                    awards: lottery.data.lists
                },
                this.initAdards(this);
                this.getLists('');
                // console.log(lottery)
                resolve()
            })
        })
    },
    // 分析是否可以分享获取次数，并取得对应次数（以前是getcount接口，现在改为获取记录表数量getjlinfo）
    getCount(actid, data) {
        return new Promise(resolve => {
            zg99Request({
                url: `/index/choujiang/getjlinfo?actid=${actid}&callback=&shijian=${Date.parse(new Date()) / 1e3}&`,
                type: 'GET',
                dataType: 'jsonp',
                data,
            }).then(res => {
                let { total } = app.methods.getAPIReturn(res);
                resolve(total)
            })
        })
    },
    //获取中奖列表
    getLists: function (phone) {
        new Promise((resolve, reject) => {
            zg99Request({
                url: `/index/choujiang/getjlinfo?actid=${this.data.prizes.actid}&callback=&shijian=${Date.parse(new Date()) / 1e3}&`,
                type: 'GET',
                dataType: 'jsonp',
                data: {
                    phone: phone,
                    limits: 30
                },
            }).then(res => {
                let resv = app.methods.getAPIReturn(res);
                this.setData({
                    winners: resv.lists
                })
                resolve()
            }).catch(err => {
                console.log(err)
                resolve()
            })
        })
    },
    //转盘
    initAdards: function () {
        var e = this,
            n = e.data.prizes.lists,
            t = n.length,
            i = 360 / t,
            s = i - 90,
            r = [],
            d = 1 / t;
        e.setData({
            btnDisabled: app.awardsConfig.chance ? "" : "disabled"
        });
        xhs.createCanvasContext("lotteryCanvas");
        for (var o = 942.47778 / t, g = 0; g < t; g++) {
            var l = "rgba(255,203,30,0.5)";
            var arrcolor = ['#fef2b8', '#7dd2f9', '#7beedf', '#8E94FD', '#F1D5B0', '#FFF3F3', '#F76A93'];
            if (t % 2 == 0) {
                l = g % 4 == 1 ? arrcolor[1] : g % 4 == 2 ? arrcolor[2] : g % 4 == 3 ? arrcolor[3] : arrcolor[0]
            } else if (t % 3 == 0) {
                var u = g % 2;
                l = g % 3 == 1 ? arrcolor[1] : g % 3 == 2 ? arrcolor[2] : arrcolor[0]
            } else if (t % 5 == 0) {
                l = g % 5 == 1 ? arrcolor[1] : g % 5 == 2 ? arrcolor[2] : g % 5 == 3 ? arrcolor[3] : g % 5 == 4 ? arrcolor[4] : arrcolor[0]
            } else if (t % 7 == 0) {
                l = g % 7 == 1 ? arrcolor[1] : g % 7 == 2 ? arrcolor[2] : g % 7 == 3 ? arrcolor[3] : g % 7 == 4 ? arrcolor[4] : g % 7 == 5 ? arrcolor[5] : g % 7 == 6 ? arrcolor[6] : arrcolor[0]
            } else {
                l = g % 4 == 1 ? arrcolor[1] : g % 4 == 2 ? arrcolor[2] : g % 4 == 3 ? arrcolor[3] : arrcolor[0]
            }
            r.push({
                k: g,
                itemWidth: o + "px",
                item2BgColor: l,
                item2Deg: g * i + 90 - i / 2 + "deg",
                item2Turn: g * d + d / 2 + "turn",
                ttt: "",
                tttSkewX: 4 * t + "deg",
                afterDeg: s + "deg",
                turn: g * d + "turn",
                lineTurn: g * d + d / 2 + "turn",
                //award: n[g].name + "等奖",// 改奖项信息
                award: n[g].name, // 改奖项信息--e.data.prizes.lists[g].name,
                pic: n[g].pic
            });
        }
        e.setData({
            awardsLen: r.length,
            awardsList: r
        });
    },
    // 奖品列表排序
    compare(attr) {
        return function (a, b) {
            const value1 = a[attr];
            const value2 = b[attr];
            return value1 - value2
        }
    },
    // 年月日时分秒的字符串转成时间戳
    formatDate: function (time) {
        var date = new Date(time);
        var time = date.getTime();
        return time;
    },
    //关闭规则
    close_rules: function () {
        this.setData({
            rules_flag: false
        })
    },
    //打开规则
    open_rules: function () {
        this.setData({
            rules_flag: true
        })
    },
    //是否有抽奖机会
    async getLottery_true() {
        if (!status) {
            let now_time = new Date().getTime() / 1000;
            if (now_time < this.data.start_time) {
                xhs.showToast({
                    title: '活动时间还未开始，耐心等待！',
                    duration: 3000,
                    icon: 'none'
                });
                return false;
            } else if (now_time > this.data.end_time) {
                xhs.showToast({
                    title: '活动已结束，不可再参与抽奖，如已参加过活动，请点击个人中心查看中奖信息！',
                    duration: 3000,
                    icon: 'none'
                });
                return false;
            }
            if (!this.data.myPhone) {
                this.setData({
                    isShowAuth: !0,
                });
            } else {
                if (share && Number(this.data.total) > 0) {
                    // 设置状态为正在抽奖中
                    status = true;
                    if (user.user?.user?.phone) {
                        let cjRes = await this.choujiang();
                        let wrRes = await this.writeJl();
                    } else {
                        const xzrPhone = (!share || (share && isMe)) ? undefined : this.data.options.xzrPhone;
                        let zhuceRes = await this.zhuce(xzrPhone);
                        user = await app.methods.getphonestatusCX(this.data.myPhone, this.data.prizes.actid, 'choujiang');
                        if (zhuceRes == 'ok') {
                            let cjRes = await this.choujiang();
                            let wrRes = await this.writeJl();
                            let zlUserInfo = await app.methods.getphonestatusCX(xzrPhone, this.data.prizes.actid, 'choujiang');
                            let xzCishu = zlUserInfo.user ? zlUserInfo?.user?.user?.cjcishu : '';
                            // console.log(xzCishu)
                            await this.update(xzrPhone, (Number(xzCishu) + 1));
                            // await this.update(1);
                        } else {
                            xhs.showToast({
                                title: '失败，稍后重试',
                                icon: 'error',
                                duration: 2000
                            });
                        }
                    }
                } else if (share && Number(this.data.total) <= 0) {
                    xhs.showToast({
                        title: '好友助力获次数',
                        icon: 'error',
                        duration: 2000
                    });
                } else {
                    // 设置状态为正在抽奖中
                    if (!user?.user?.user) {
                        let zhuceRes = await this.zhuce();
                    }
                    let cjRes = await this.choujiang();
                    let wrRes = await this.writeJl();
                    status = true;
                }
            }
        } else {
            xhs.showToast({
                title: '正在抽奖请稍后',
                icon: 'none',
                duration: 2000,
            });
        }
    },
    // 下拉刷新
    async onPullDownRefresh() {
        const {
            myPhone
        } = this.data;
        const {
            lx
        } = this.data.options;
        if (lx && myPhone) {
            let xzCishu = await this.getCount(this.data.prizes.actid, {
                phone: myPhone,
                tabnum: 1,
                limits: 200
            });
            xzCishu = xzCishu ? xzCishu : 0;
            user = await app.methods.getphonestatusCX(myPhone, this.data.prizes.actid, 'choujiang')
            cjCishu = user.user ? user?.user?.user?.cjcishu : ''
            if (!isMe) {
                if (this.data.options.xzrPhone && !user.user) {
                    xhs.showToast({
                        title: '抽奖一次即可完成助力~',
                        icon: 'none',
                        duration: 2000
                    })
                } else if (this.data.options.xzrPhone && user.user.user.xzrPhone) {
                    xhs.showToast({
                        title: user.xzrPhone !== this.data.options.xzrPhone ? '已为其他好友助力' : '已为好友助力',
                        icon: 'error',
                        duration: 2000
                    })
                }
            }
            if(!user?.user?.user?.zhuanye && this.data.options.rq == 'gx') {
                this.setData({
                    gxxx: true
                })
            }
            const total = user.user ? Number(cjCishu) - Number(xzCishu) : 1;
            this.setData({
                total
            })
        }
    },
    // 注册
    zhuce(xzrPhone) {
        return new Promise((resolve, reject) => {
            var phonegsd = null
            if (!this.data.getIdentity.zzid && this.data.getIdentity.fenbu == '河北') {
                phonegsd = getApp().methods.get_phone_attribution(this.data.myPhone)
            }
            if (phonegsd && phonegsd.province != '河北') var thisRandom = parseInt(Math.random() * 10);
            zg99Request({
                url: `/index/choujiang/register?actid=${this.data.prizes.actid}&callback=&shijian=${Date.parse(new Date()) / 1000}&`,
                type: 'GET',
                dataType: 'jsonp',
                data: {
                    xzrPhone,
                    cjcishu: 1,
                    phone: this.data.myPhone,
                    gonghao: this.data.getIdentity.crm ? this.data.getIdentity.crm : this.data.getIdentity.username,
                    fenxiao: this.data.getIdentity.fenxiao,
                    xulieName: this.data.getIdentity.xulie_name,
                    realname: this.data.getIdentity.realname,
                    isagree: true,
                    orgn: phonegsd ? phonegsd.province == '河北' ? this.data.getIdentity.orgn = getApp().globalData.config.zzidAerpdqm[phonegsd.city].zzid : getApp().globalData.config.zzidAerpdqm[getApp().globalData.config.zzidAerpdqm['random'][thisRandom]].zzid : this.data.getIdentity.zzid,
                    erpdqm: phonegsd ? phonegsd.province == '河北' ? this.data.getIdentity.orgn = getApp().globalData.config.zzidAerpdqm[phonegsd.city].erpdqm : getApp().globalData.config.zzidAerpdqm[getApp().globalData.config.zzidAerpdqm['random'][thisRandom]].erpdqm : this.data.getIdentity.erpdqm,
                    myname: this.data.myPhone
                },
            }).then(res => {
                let data1 = app.methods.getAPIReturn(res);
                if (data1.status == 1) {
                    resolve('ok')
                } else {
                    resolve('nook')
                }
            })
        })
    },
    // 抽奖
    choujiang() {
        return new Promise((resolve, reject) => {
            zg99Request({
                url: `/index/choujiang/lottery?actid=${this.data.prizes.actid}&callback=&shijian=${Date.parse(new Date()) / 1e3}&`,
                type: 'GET',
                dataType: 'jsonp',
                data: {
                    myname: this.data.myPhone,
                    isagree: true,
                    phone: this.data.myPhone
                },
            }).then(res => {
                let data1 = app.methods.getAPIReturn(res);
                if (data1.status == 1) {
                    this.setData({
                        prize_num: data1.prizeid,
                        ['result.prizeid']: data1.prizeid,
                        ['result.name']: data1.prizename,
                        flag: false,
                        jlid: data1.jlid
                    })
                    //从综合后台获取奖项信息-传递给个人中心页面
                    var obj = this.data.prizes.lists;
                    var flag1 = {
                        prizeid: Number(data1.prizeid)
                    };
                    var index_jx = (obj || []).findIndex((profile) => profile.prizeid === flag1.prizeid);
                    this.setData({
                        prize_num: data1.prizeid,
                        index_jx: index_jx,
                        ['result.type']: obj[index_jx].type,
                        ['result.intro']: obj[index_jx].intro,
                        ['result.pic']: obj[index_jx].pic,
                        ['result.img']: obj[index_jx].img,
                        ['result.name']: obj[index_jx].name,
                        items: obj[index_jx].arr_cname
                    })
                    //如何返回多个数据
                    if (this.data.prizes.mode == 1) {
                        this.getLottery();
                    } else if (this.data.prizes.mode == 2) {
                        this.startrolling();
                    }
                    resolve([this.data.prize_num, this.data.result, this.data.items])
                } else {
                    xhs.showToast({
                        title: data1.msg,
                        icon: 'none',
                        duration: 2000
                    })
                }
            })
        })
    },
    // 写入记录表
    writeJl() {
        return new Promise(resolve => {
            zg99Request({
                url: `/index/choujiang/updatejlb?actid=${this.data.prizes.actid}&callback=&shijian=${Date.parse(new Date()) / 1e3}&`,
                type: 'GET',
                dataType: 'jsonp',
                data: {
                    phone: this.data.myPhone,
                    pic: this.data.result.pic,
                    intro: this.data.result.intro,
                    img: this.data.result.img,
                },
            }).then(res => {
                let data1 = app.methods.getAPIReturn(res);
                resolve(data1)
            })
        })
    },
    // 修改用户表
    update(phone, cishu) {
        return new Promise(resolve => {
            zg99Request({
                url: `/index/choujiang/updateuser/?actid=${this.data.prizes.actid}&callback=&shijian=${Date.parse(new Date()) / 1e3}&`,
                type: 'GET',
                dataType: 'jsonp',
                data: {
                    phone,
                    cjcishu: cishu,
                },
            }).then(res => {
                let newStr = app.methods.getAPIReturn(res);
                resolve(newStr)
            }).catch(err => {
                console.log(err)
            })
        })
    },
    //转盘抽奖
    getLottery: function () {
        var e = this,
            n = app.awardsConfig,
            t = n.awards.length;
        e.setData({
            prize: ''
        })
        // 执行完lottery之后-执行抽奖动作
        var i = e.data.prize_num;
        var obj = e.data.prizes.lists;
        var flag1 = {
            prizeid: parseInt(i)
        };
        var index_jx = (obj || []).findIndex((profile) => profile.prizeid === flag1.prizeid);
        let p = new Promise((resolve, reject) => {
                setTimeout(async function () {
                    // console.log(e.data.result.prizeid)
                    if(obj[index_jx].spcode) {
                        let result1 = await app.methods.sfkkMethod(obj[index_jx].spcode, e.data.myPhone)
                        if(result1.data.length == 0) {
                            let result2 = await app.methods.zidongkaike(obj[index_jx].spcode, e.data.myPhone, '抽奖活动', 'heboffcn微信小程序', '抽奖活动')
                        }
                    }
                    e.setData({
                        ['result.prizeid']: i,
                        ['result.type']: obj[index_jx].type,
                        ['result.name']: obj[index_jx].name,
                        ['result.img']: obj[index_jx].img,
                        ['result.intro']: obj[index_jx].intro,
                        ['result.pic']: obj[index_jx].pic,
                        prize: obj[index_jx].name,
                        result_show: true,
                        flag: false
                    })
                    // 在抽奖结束后更新 total
                    if (share) {
                        let xzCishu = await e.getCount(e.data.prizes.actid, {
                            phone: e.data.myPhone,
                            tabnum: 1,
                            limits: 200
                        });
                        xzCishu = xzCishu ? xzCishu : 0;
                        user = await app.methods.getphonestatusCX(e.data.myPhone, e.data.prizes.actid, 'choujiang');
                        cjCishu = user.user ? user?.user?.user?.cjcishu : '';
                        e.setData({
                            total: Number(cjCishu) - Number(xzCishu),
                        });
                        if(!user?.user?.user?.zhuanye && e.data.options.rq == 'gx') {
                            e.setData({
                                gxxx: true
                            })
                        }
                    }
                    // 清除状态标志
                    status = false;
                }, 4300)
                resolve()
            })
            .then((res) => {
                return new Promise((resolve, reject) => {
                    app.runDegs = app.runDegs || 0;
                    app.runDegs = app.runDegs + (360 - app.runDegs % 360) + (2160 - (i - 1) * (360 / t)); //因为i--奖项设置从1开始，不是0开始
                    var s = xhs.createAnimation({
                        duration: 4e3,
                        timingFunction: "ease"
                    });
                    e.animationRun = s, s.rotate(app.runDegs).step(), e.setData({
                        animationData: s.export(),
                        btnDisabled: "disabled",
                        sliderDisabled: "disabled"
                    }), setTimeout(function () {
                        n.chance && e.setData({
                            btnDisabled: "",
                            sliderDisabled: ""
                        });
                        resolve()
                    }, 4e3);
                })
            })
            .then((res) => {
                e.getLists('')
            })
    },
    //九宫格
    //开始滚动
    startrolling: function () {
        this.data.runs_now = 0;
        if (this.data.amplification_index !== -1) {
            this.data.amplification_index--;
        }
        //当前可以点击的状态下
        if (this.data.roll_flag) {
            this.data.roll_flag = false;
            //启动滚盘，注，若是最终后台无返回就不好意思里
            this.setData({
                minturns: parseInt(Math.random() * 10 + 4),
                prize_jgg: '',
                flag: false
            })
            this.rolling();
        }
    },
    //滚动轮盘的动画效果
    rolling: function (amplification_index) {
        this.data.myInterval = setTimeout(() => {
            this.rolling()
            this.data.time++
        }, this.data.speed);
        this.data.runs_now++; //已经跑步数加一
        this.data.amplification_index++; //当前的加一
        // console.log(this.data.amplification_index)
        //获取总步数，接口延迟问题，所以最后还是设置成1s以上
        var count_num = this.data.minturns * this.data.max_number + this.data.prize_num - this.data.last_index;
        // console.log("当前~" + this.data.amplification_index + "目标~" + this.data.prize_num + "跨越~" + count_num + "上次~" + this.data.last_index)
        //上升期间
        if (this.data.runs_now <= (count_num / 3) * 2) {
            this.data.speed -= 30; //加速
            if (this.data.speed <= this.data.max_speed) {
                this.data.speed = this.data.max_speed; //最高速度为40；
            }
        }
        //抽奖结束
        else if (this.data.runs_now >= count_num) {
            clearInterval(this.data.myInterval);
            this.data.roll_flag = true;
            this.setData({
                last_index: this.data.amplification_index
            })
            setTimeout(async () => {
                // console.log(this.data.result.prizeid)
                if(this.data.prizes.lists[this.data.prize_num - 1].spcode) {
                    let result1 = await app.methods.sfkkMethod(this.data.prizes.lists[this.data.prize_num - 1].spcode, this.data.myPhone)
                    // console.log(result1)
                    if(result1.data.length == 0) {
                        let result2 = await app.methods.zidongkaike(this.data.prizes.lists[this.data.prize_num - 1].spcode, this.data.myPhone, '抽奖活动', 'heboffcn微信小程序', '抽奖活动')
                        // console.log(result2)
                    }
                }
                this.setData({
                    result_show: true,
                })
                // 在抽奖结束后更新 total
                if (share) {
                    let xzCishu = await this.getCount(this.data.prizes.actid, {
                        phone: this.data.myPhone,
                        tabnum: 1,
                        limits: 200
                    });
                    xzCishu = xzCishu ? xzCishu : 0;
                    user = await app.methods.getphonestatusCX(this.data.myPhone, this.data.prizes.actid, 'choujiang');
                    cjCishu = user.user ? user?.user?.user?.cjcishu : '';
                    this.setData({
                        total: Number(cjCishu) - Number(xzCishu)
                    });
                    if(!user?.user?.user?.zhuanye && this.data.options.rq == 'gx') {
                        this.setData({
                            gxxx: true
                        })
                    }
                }
                // 清除状态标志
                status = false;
            }, 250)
        }
        //下降期间
        else if (count_num - this.data.runs_now <= 10) {
            this.data.speed += 20;
        }
        //缓冲区间
        else {
            this.data.speed += 10;
            if (this.data.speed >= 100) {
                this.data.speed = 100; //最低速度为100；
            }
        }
        // console.log(this.data.amplification_index, this.data.max_number - 1)
        if (this.data.amplification_index > this.data.max_number - 1) { //判定！是否大于最大数
            this.data.amplification_index = 0;
        }
        this.setData(this.data);
    },
    watchmyPhone: async function (value) {
        if (value.myPhone) {
            this.setData({
                isShowAuth: !1,
                isPrivacyAuthorization: !1,
                myPhone: value.myPhone,
            })
            user = await app.methods.getphonestatusCX(value.myPhone, this.data.prizes.actid, 'choujiang')
            if (share) {
                let xzCishu = await this.getCount(this.data.prizes.actid, {
                    phone: value.myPhone
                });
                xzCishu = xzCishu ? xzCishu : 0;
                // user = await app.methods.getphonestatusCX(value.myPhone, this.data.prizes.actid, 'choujiang')
                // console.log(user)
                cjCishu = user.user ? user?.user?.user?.cjcishu : ''
                if (!isMe) {
                    if (this.data.options.xzrPhone && !user.user) {
                        xhs.showToast({
                            title: '抽奖一次即可完成助力~',
                            icon: 'none',
                            duration: 2000
                        })
                    } else if (this.data.options.xzrPhone && user.user.user.xzrPhone) {
                        xhs.showToast({
                            title: user.xzrPhone !== this.data.options.xzrPhone ? '已为其他好友助力' : '已为好友助力',
                            icon: 'error',
                            duration: 2000
                        })
                    }
                }
                const total = user.user ? Number(cjCishu) - Number(xzCishu) : 1;
                if(!user?.user?.user?.zhuanye) {
                    this.setData({
                        gxxx: true
                    })
                }
                this.setData({
                    total
                })
            }
        }
    },
    // 免费公开课，跳转19课堂
    open_freecourse: function (res) {
        var e = this;
        xhs.navigateToMiniProgram({
            appId: res.currentTarget.dataset.appid,
            path: res.currentTarget.dataset.url,
            envVersion: "release",
            success: function () {
                e.setData({
                    result_show: false
                })
            }
        });
        e.getLists('');
    },
    //
    //手动开课+未中奖 关闭中奖结果
    close_result: function (res) {
        var e = this;
        e.setData({
            result_show: false
        })
        e.getLists('');
    },
    //跳转我的抽奖页面
    gotomycenter: function (a) {
        //查接口 查是否抽奖--设置result
        // console.log(e.data.myPhone)
        let p = new Promise((resolve, reject) => {
                xhs.getStorage({
                    key: 'myPhone',
                    success: ((res) => {
                        this.setData({
                            myPhone: res.data
                        })
                        resolve()
                    }),
                    fail: ((err) => {
                        this.setData({
                            isShowAuth1: !0
                        })
                        reject('未授权')
                    })
                })
            })
            .then((res) => {
                return new Promise((resolve, reject) => {
                    zg99Request({
                        url: `/index/choujiang/getjlinfo?actid=${this.data.prizes.actid}&callback=&shijian=${Date.parse(new Date()) / 1000}&`,
                        type: 'GET',
                        dataType: 'jsonp',
                        data: {
                            phone: this.data.myPhone,
                            limits: 200
                        },
                    }).then(res => {
                        let resv = app.methods.getAPIReturn(res);
                        if (resv.status == 1) {
                            var obj = this.data.prizes.lists;
                            // console.log(obj)
                            var flag1 = {
                                result: resv.lists
                            };
                            this.setData({
                                result: resv.lists
                            })
                        }
                        resolve(this.data.result)
                    }).catch(err => {
                        console.log(err)
                    })
                })
            })
            .then((res) => {
                // console.log(this.data.result)
                if (JSON.stringify(this.data.result) === '{}') {
                    let now_time = new Date().getTime() / 1000;
                    if (now_time < this.data.start_time) {
                        //未到时间
                        xhs.showToast({
                            title: '活动时间还未开始，耐心等待！',
                            duration: 3000,
                            icon: 'none'
                        })
                        return false;
                    } else if (now_time > this.data.end_time) {
                        //已结束
                        xhs.showToast({
                            title: '活动已结束，您未参与过该活动，暂无中奖记录！\n如有疑问，请联系管理员进行活动记录查询！',
                            duration: 3000,
                            icon: 'none'
                        })
                        return false;
                    }
                    xhs.showToast({
                        title: '您还没有参加抽奖呦！\n抽奖完成再查看中奖记录吧',
                        duration: 3000,
                        icon: 'none'
                    })
                } else {
                    let t = {
                        options: this.data.options, //options 包含id gonghao  fenxiao
                        myPhone: this.data.myPhone,
                        actid: this.data.prizes.actid,
                        result: this.data.result,
                        prizes: this.data.prizes,
                        flag: false,
                    };
                    xhs.redirectTo({
                        url: "./mylottery?data=" + encodeURIComponent(JSON.stringify(t))
                        //传递字符串太长会被截取，所以需要转码，接收后解码即可
                    });
                }
            })
    },
    //盲盒
    blind_lottery: function () {
        let e = this;
        e.setData({
            blind_result: e.data.prizes.lists[e.data.prize_num].name
        })
    },
    //姓名
    nameChange: function (t) {
        let e = this;
        e.setData({
            shname: t.detail.value
        })
        if (!e.data.shname) {
            xhs.showToast({
                title: '请输入姓名',
                icon: 'none',
                duration: 1000
            })
            return false;
        }
        var name_re = /^[\u4e00-\u9fa5]{0,}$/;
        if (!name_re.test(e.data.shname)) {
            xhs.showToast({
                title: '请输入正确的姓名',
                icon: 'none',
                duration: 1000
            })
            return false;
        }
    },
    //地址
    addressChange: function (t) {
        let e = this;
        e.setData({
            address: t.detail.value
        })
        if (!e.data.address) {
            xhs.showToast({
                title: '请正确填写地址，否则无法寄出奖品呦',
                icon: 'none',
                duration: 1000
            })
            return false;
        }
    },
    //实物邮寄
    submit_address: function (jlid) {
        if (!this.data.shname) {
            xhs.showToast({
                title: '请输入姓名',
                icon: 'none',
                duration: 1000
            })
            return false;
        }
        if (!this.data.address) {
            xhs.showToast({
                title: '请输入地址',
                icon: 'none',
                duration: 1000
            })
            return false;
        }
        zg99Request({
            url: `/index/choujiang/updatejlb?actid=${this.data.prizes.actid}&callback=&shijian=${Date.parse(new Date()) / 1e3}&`,
            type: 'GET',
            dataType: 'jsonp',
            data: {
                phone: this.data.myPhone,
                shname: this.data.shname,
                address: this.data.address,
                xiangmu: this.data.item,
            },
        }).then(res => {
            let resv = app.methods.getAPIReturn(res);
            xhs.showToast({
                title: '提交成功了，耐心等等快递向您奔赴吧！',
                duration: 3000,
                icon: 'none'
            })
            this.setData({
                result_show: false
            })
            this.getLists();
        })
    },
    // 高校活动信息提交
    gxhdtj: function(e) {
        if(!this.data.nianji || !this.data.majorvalue) {
            xhs.showToast({
              title: !this.data.nianji ? '请选择年级' : '请选择专业',
              icon: 'error',
              duration: 2000,
              mask: true
            })
            return false;
        }
        zg99Request({
            url: `/index/choujiang/updateuser/?actid=${this.data.prizes.actid}&callback=&shijian=${Date.parse(new Date()) / 1e3}&`,
            type: 'GET',
            dataType: 'jsonp',
            data: {
                phone: this.data.myPhone,
                nianji: this.data.nianji,
                zhuanye: this.data.majorvalue,
            },
        }).then(res => {
            let newStr = app.methods.getAPIReturn(res);
            // console.log(newStr)
            if(newStr.status == 1) {
                xhs.showToast({
                  title: '补充信息完成',
                })
                this.setData({
                    gxxx: false,
                    result_show: false,
                })
            } else {
                xhs.showToast({
                    title: newStr.msg,
                })
            }
        }).catch(err => {
            console.log(err)
        })
    },
    // 选择专业
    m_selectSearch_touch: function (t) {
        var e = t.detail.selText;
        // console.log(e)
        this.setData({
            majorvalue: e
        });
    },
    m_select_touch: async function (t) {
        this.setData({
            nianji: t.detail.selectText
        })
    },
    async user_login(e){
        if(typeof e.detail == 'boolean') {
            this.setData({
                isShowAuth: e.detail
            })
        } else {
            this.setData({
                myPhone: e.detail
            })
            user = await app.methods.getphonestatusCX(e.detail, this.data.prizes.actid, 'choujiang')
        }
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
        const {
            myPhone,
        } = this.data;
        const { id, gh, fx, lx, rq, hdid } = this.data.options;
        let path = `/packageA/cj/index?id=${id}&gh=${gh}&fx=${fx}&xzrPhone=${myPhone}`;
        return {
            title: this.data.k_name ? this.data.k_name : '邀您参与中公抽奖活动',
            path,
            imageUrl: this.data.k_url ? this.data.k_url : '',
        }
    }
})